package com.api.core.filter;

import com.api.core.model.FormAjaxReturn;
import com.api.core.model.ResponseModel;
import com.api.core.util.RspUtil;
import com.api.core.util.WebUtil;
import com.api.entity.SystemUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.regex.Pattern;

/**
 * 请求过滤器
 */
@Slf4j
public class RequestValidationFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) {
        log.info("初始化->RequestValidationFilter");
    }


    /**
     * 过滤小程序请求
     */
    private static final Boolean ALLOWED_PATHSb (String str){
        List<String> list = Collections.unmodifiableList(Arrays.asList("/linkUser", "/linkUrl"));
        for(int i=0; i < list.size(); i++){
            if (Pattern.matches(".*("+list.get(i)+").*", str)) {
                return true;
            }
        }
        return false;
    }


    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse rsp = (HttpServletResponse)response;
        String path = req.getRequestURI().substring(req.getContextPath().length()).replaceAll("[/]+$", "");
        if (ALLOWED_PATHSb(path)) {
//            System.out.println("这里是不需要处理的url进入的方法");
            String token = req.getHeader("Authorization");
            if(StringUtils.isEmpty(token)||null==token) {
                RspUtil.returnObject(rsp,new ResponseModel(-2,"token不能为空"));
                return;
            }
//            UserLoginModel model = userService.getUserModel(token);
//            if(null==model)
//            {
//                RspUtil.returnObject(rsp,new ResponseModel(-2,"token已失效"));
//                return;
//            }
//            request.setAttribute("userModel",model);
            chain.doFilter(request, response);
        }else {
            SystemUser userInfo = (SystemUser)req.getSession().getAttribute("userInfo");
            System.out.println("过滤器发现用户="+userInfo);
            if (null!=userInfo){
                chain.doFilter(request, response);
                return;
            }
            FormAjaxReturn arf = new FormAjaxReturn();
            arf.setMessage("操作失败！登录已失效，请重新登陆！");
            arf.setStatusCode(400);
            WebUtil.returnMsg(rsp, arf);
        }


    }

    @Override
    public void destroy() {

    }



}
